<?php

namespace app\common\library;

use app\admin\model\Setting;
use app\admin\model\Transaction;
use app\admin\model\user\Balance;
use app\admin\model\user\Extend;
use app\admin\model\ReservePays;
use Carbon\Carbon;
use EasyWeChat\Factory;
use fast\Http;
use tests\thinkphp\library\think\behavior\Three;
use think\Db;
use think\Env;

class Pay
{
    protected $_userId = 0;
    protected $_reserveId = 0;
    public function __construct($userId = 0, $reserveId = 0)
    {
        if (empty($userId) || empty($reserveId)) {
            throw new \Exception('初始化Pay缺少参数');
        }
        $this->_userId = $userId;
        $this->_reserveId = $reserveId;
    }
    
    // 卡支付
    public function cardPay($cardId, $consumeHour)
    {
        if (empty($cardId) || empty($consumeHour)) {
            throw new \Exception('缺少卡ID或时长参数');
        }

        $userCard = \app\admin\model\user\Card::get($cardId);
        if ($userCard->total_hour < $userCard->hasconsumedhour + $consumeHour) {
            throw new \Exception('卡时长不足');
        }
        $userCard->hasconsumedhour = $userCard->hasconsumedhour + $consumeHour;
        $userCard->save();

        // 增加明细记录
        $reservePays = new ReservePays();
        $reservePays->reserve_id = $this->_reserveId;
        $reservePays->user_id = $this->_userId;
        $reservePays->pay_amount = $consumeHour;
        $reservePays->pay_way = 1;
        $reservePays->pay_id = $cardId;
        $reservePays->pay_status = 1;
        $reservePays->save();
    
    }

    public function cardData($reserve)
    {
        // 查找明细表
        $wheres = [
            'reserve_id' => $this->_reserveId,
            'user_id' => $this->_userId,
            'pay_way' => 1,
            'pay_id'  => $reserve->card_id,
            'pay_status' => 1,
        ];
        $reservePay = ReservePays::where($wheres)->find();
        // 未找到数据时，使用老方式
        if (!$reservePay) {
            // throw new \Exception('未找到有效的卡券支付信息');
            $start = Carbon::parse($reserve->starttime);
            $end = Carbon::parse($reserve->endtime);

            if ($end->minute == 29 || $end->minute == 59) {
                $end->addMinute();
            }

            $consumeHour = number_format($end->diffInMinutes($start) / 60, 2);
        } else {
            $consumeHour = $reservePay->pay_amount;
        }

        return $consumeHour;
    }

    public function cardRefund($reserve)
    {
        // 查找明细表
        $wheres = [
            'reserve_id' => $this->_reserveId,
            'user_id' => $this->_userId,
            'pay_way' => 1,
            'pay_id'  => $reserve->card_id,
            'pay_status' => 1,
        ];
        $reservePay = ReservePays::where($wheres)->find();
        // 未找到数据时，使用老方式
        if (!$reservePay) {
            // throw new \Exception('未找到有效的卡券支付信息');
            $start = Carbon::parse($reserve->starttime);
            $end = Carbon::parse($reserve->endtime);

            if ($end->minute == 29 || $end->minute == 59) {
                $end->addMinute();
            }

            $consumeHour = number_format($end->diffInMinutes($start) / 60, 2);
        } else {
            $consumeHour = $reservePay->pay_amount;
            // 更新状态
            $reservePay->pay_status = 0;
            $reservePay->save();
        }

        $card = \app\admin\model\user\Card::get($reserve->card_id);
        $card->hasconsumedhour -= $consumeHour;
        $card->save();
    
    }

    public function balancePay($subNum, $userExtend)
    {
        if ($userExtend->balance < $subNum) {
            throw new \Exception('余额不足');
        }
        $afterValue = $userExtend->balance - $subNum;
        $balance = new Balance();
        $lastId = $balance->insertGetId([
            'user_id' => $this->_userId,
            'type' => -1, // -1=消费
            'value' => $subNum,
            'before_value' => $userExtend->balance,
            'after_value' => $afterValue,
            'createtime' => time(),
            'updatetime' => time()
        ]);
    
        $userExtend->balance = $afterValue;
        $userExtend->save();

        return $lastId;
    }

    public function balanceData($reserve)
    {
        // 查找余额支付的数目
        $balanceInfo = Balance::where('id', $reserve->balance_id)->find();
        if (!$balanceInfo) {
            return 0;
        }
        
        return $balanceInfo->value; 
    }

    public function balanceRefund($reserve)
    {
        // 查找余额支付的数目
        $balanceInfo = Balance::where('id', $reserve->balance_id)->find();
        if (!$balanceInfo) {
            throw new \Exception('未找到有效的余额支付信息');
        }

        $userExtend = Extend::where('user_id', $this->_userId)->find();
        $afterValue = $userExtend->balance + $balanceInfo->value;

        Balance::create([
            'user_id' => $this->_userId,
            'type' => 2, //系统返还
            'value' => $balanceInfo->value,
            'before_value' => $userExtend->balance,
            'after_value' => $afterValue,
        ]);

        $userExtend->balance = $afterValue;
        $userExtend->save(); 
    }

    public function wechatPay()
    {
    
    }

    public function wechatData($reserve)
    {
        $trans  =Transaction::get($reserve->transaction_id);
        if (!$trans) {
            return 0;
        }

        return $trans->fee;
    }

    public function wechatRefund($reserve)
    {
        // 把微信支付证书cert和key放到文件里
        $certFile = APP_PATH . '/cert/apiclient_cert.pem';
        $keyFile = APP_PATH . '/cert/apiclient_key.pem';

        $appId = Env::get('mp.appid');
        $payMerchantId = Env::get('mp.pay_merchant_id');
        $payApiKey = Env::get('mp.pay_api_key');

        $config = [
            'app_id'             => $appId,
            'mch_id'             => $payMerchantId,
            'key'                => $payApiKey,
            'cert_path'          => $certFile,
            'key_path'           => $keyFile,
            'notify_url'         => '',
            'sandbox' => false,
        ];

        $app = Factory::payment($config);

        $trans  =Transaction::get($reserve->transaction_id);

        $testRefund = Env::get('common.test_refund');
        $testPay = Env::get('common.test_pay');

        $refundFee = $trans->fee * 100;
        if ($testPay) {
            $refundFee = 1;
        }


        // 退款接口多次请要都可以
        if ($testRefund) {
            $result['return_code'] = 'SUCCESS';
        } else {
            $result = $app->refund->byTransactionId($trans->transaction_no, $trans->out_trade_no, $refundFee, $refundFee);
        }

        if ('SUCCESS' == $result['return_code']) {
            $trans->status = 3; // 标识为退款
            $trans->save();
        } else if ('FAIL' == $result['return_code']) {  // 微信支付平台报错
            throw new \Exception($result['return_msg']);
        } else {
            throw new \Exception('出现服务器错误，请联系管理员');
        }
    }

    public function couponPay($couponid)
    {
        if (is_numeric($couponid) and $couponid > 0) {
            $coupon = \app\admin\model\user\Coupon::get($couponid);
            $coupon->is_used = 1;
            $coupon->save();
        }
    }

    public function couponRefund($couponid)
    {
        if (is_numeric($couponid) and $couponid > 0) {
            $coupon = \app\admin\model\user\Coupon::get($couponid);
            $coupon->is_used = 0;
            $coupon->save();
        }
    
    }
}
